﻿using Infrastructure.Dao;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WsdShop.IService;
using WsdShop.Model;
using WsdShop.Model.Enum;

namespace WsdShop.Service
{
    public class DrawService : IDrawService
    {
        private SqlSugarClient db;
        public DrawReward Draw(int actId)
        {
            using (var db = DbConfig.GetInstance())
            {
                Random rd = new Random();
                int randomNum = rd.Next(1, 100);
                var prize = db.Queryable<DrawReward>().FirstOrDefault(p => p.DrawId == actId && p.StartValue <= randomNum && p.EndValue >= randomNum && p.Count-p.WinningCount>0);
                if (prize == null)
                    return null;
                if (prize.RewardType == RewardType.实体商品)
                {
                   var pro= db.Queryable<Product_Spec>().SingleOrDefault(t => t.Id == prize.ProductSecpId);
                    if (pro == null)
                    {
                        return null;
                    }
                }
                else if (prize.RewardType == RewardType.优惠券)
                {
                    var pro = db.Queryable<Coupon>().SingleOrDefault(t => t.Id == prize.ProductSecpId);
                    if (pro == null)
                    {
                        return null;
                    }
                }
                prize.WinningCount = prize.WinningCount +1;
                db.Update(prize);
                if (prize.Count-prize.WinningCount < 0)
                {
                    return null;
                }
                return prize;
            }
        }


        public void CreateMemberCoupons(List<MemberCoupon> list)
        {
            using (var db = DbConfig.GetInstance())
            {
                db.InsertRange(list);
            }
        }

        /// <summary>
        /// 获取所有抽奖
        /// </summary>
        /// <returns></returns>
        public List<Model.Draw> GetDrawListAll()
        {
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<Model.Draw>()
                      .OrderBy(o => o.AddTime, OrderByType.Desc).ToList();
                return list;
            }
        }

        public DrawReward Draw1(int actId)
        {
            using (var db = DbConfig.GetInstance())
            {
                var prize = db.Queryable<DrawReward>().OrderBy(p => p.WinRate, OrderByType.Desc).FirstOrDefault(p => p.DrawId == actId && p.Count - p.WinningCount > 0);
                if (prize == null)
                {
                    return null;
                }
                prize.WinningCount = prize.WinningCount + 1;
                db.Update(prize);
                if (prize.Count-prize.WinningCount < 0)
                {
                    return null;
                }
                return prize;
            }
        }
    }
}
